<template>
  <div class="process borderbottom">
    <div class="process-title">
      <div></div>
      <div>工艺指示书</div>
      <i class="el-icon-circle-plus-outline pointer" style="color: #409eff; font-size: 24px; margin-left: 10px" @click="onClickDialog(-1)" v-if="!disabled"></i>
    </div>
    <div class="process-canvas" v-for="(item, index) in data" :key="index">
      <div class="process-canvas-left">
        <div class="process-canvas-left-border" @click="MouseClick($event, index)">
          <img :src="item.img" alt="" />
          <div class="process-canvas-left-border-label" v-for="(e, idx) in item.labels" :key="idx" :style="{ top: e.y + 'px', left: e.x + 'px' }" @click.stop>
            {{ idx + 1 }}
          </div>
        </div>
        <div class="process-canvas-left-edit">
          <el-button
            type="primary"
            plain
            size="default"
            @click="onClickDialog(index)"
            v-if="!disabled"
            >修改</el-button
          >
          <el-button
            type="danger"
            plain
            size="default"
            @click="onDel(index)"
            v-if="!disabled"
            >刪除</el-button
          >
        </div>
      </div>
      <div class="process-canvas-right">
        <div class="process-canvas-right-div">
          <div style="width: 100px">图片名称</div>
          <el-input
            style="width: 300px"
            v-model="item.title"
            placeholder="请输入图片名称"
            size="normal"
            clearable
            :readonly="disabled ? 'readonly' : false"
          ></el-input>
        </div>
        <div
          class="process-canvas-right-div"
          v-for="(e, idx) in item.labels"
          :key="idx"
        >
          <div style="width: 100px">说明{{ idx + 1 }}</div>
          <!-- <el-input
            style="maxwidth: 900px"
            v-model="e.content"
            type="textarea"
            placeholder="请输入说明"
            size="normal"
            clearable
            :readonly="disabled ? 'readonly' : false"
          ></el-input> -->
          <div v-html="e.content" class="htmltext"></div>
          <div class="process-canvas-right-div-icon">
            <i
              class="el-icon-edit-outline pointer"
              style="font-size: 30px; color: #2c70d6; margin-left: 10px"
              @click="onEdit(index, idx, e.content)"
              v-if="!disabled"
            ></i>
            <i
              class="el-icon-delete pointer"
              style="font-size: 30px; color: red; margin-left: 10px"
              @click="onDelete(index, idx)"
              v-if="!disabled"
            ></i>
          </div>
        </div>
        <div
          v-if="!item.labels.length"
          style="color: red; font-weight: 800; margin: 40px 20px"
        >
          请点击左侧图片添加标注！
        </div>
      </div>
    </div>
    <el-dialog
      :modal="false"
      :close-on-click-modal="false"
      title="工艺指示书"
      :visible.sync="dialogVisible"
      width="1460px"
      :before-close="handleClose"
    >
      <div class="dialogcanvas">
        <div class="dialogcanvas-canvas">
          <canvas id="label-canvas" :width="1200" :height="600" />
        </div>
        <div class="dialogcanvas-operation">
          <el-upload
            class="upload-demo"
            action="/"
            accept=".png, .jpg"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
          >
            <el-button size="small" type="">上传图片</el-button>
          </el-upload>
          <div>
            <el-button size="small" type="" @click="moveActive(0)"
              >向下一层</el-button
            >
          </div>
          <div>
            <el-button size="small" type="" @click="moveActive(1)"
              >向下至底层</el-button
            >
          </div>
          <div>
            <el-button size="small" type="" @click="moveActive(2)"
              >向上一层</el-button
            >
          </div>
          <div>
            <el-button size="small" type="" @click="moveActive(3)"
              >向上至顶层</el-button
            >
          </div>
          <div>
            <el-button size="small" type="" @click="moveActive(4)"
              >缩小1倍</el-button
            >
          </div>
          <div>
            <el-button size="small" type="" @click="moveActive(5)"
              >删除</el-button
            >
          </div>
          <div style="margin-top: 60px">
            <el-button
              size="small"
              type="primary"
              @click="onSave"
              :loading="loadingsave"
              >保存</el-button
            >
          </div>
        </div>
      </div>
    </el-dialog>
    <el-dialog
      title="说明"
      :visible.sync="dialogVisibleText"
      width="900"
      :before-close="handleCloseHtml"
      :modal="false"
      :close-on-click-modal="false"
    >
      <div style="border: 1px solid #ccc">
        <Toolbar
          style="border-bottom: 1px solid #ccc"
          :editor="editor"
          :defaultConfig="toolbarConfig"
          :mode="mode"
        />
        <Editor
          style="height: 500px; overflow-y: hidden"
          v-model="html"
          :defaultConfig="editorConfig"
          :mode="mode"
          @onCreated="onCreated"
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCloseHtml">取 消</el-button>
        <el-button type="primary" @click="onSubmitHtml" :disabled="!html"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { uploadHomeApiupload } from "@/api";
import { base64toFile } from "@/utils/base64toFile.js";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import "@wangeditor/editor/dist/css/style.css";
export default {
  components: { Editor, Toolbar },
  props: {
    data: {
      type: Array,
      default: [],
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      editor: null,
      html: "",
      toolbarConfig: {
        excludeKeys: ["group-image", "group-video", "emotion", "fontFamily", "insertTable"],
      },
      editorConfig: { placeholder: "请输入内容..." },
      mode: "default", // or 'simple'

      dialogVisible: false,
      dialogVisibleText: false,
      loadingsave: false,
      index: -1,
      canvasObj: "",
      MouseClickE: "",
      MouseClickIndex: "",
      htmltype: "",
    };
  },
  watch: {
    data: {
      handler(newVal, oldVal) {
        this.$emit("processComponent", newVal);
      },
      deep: true, // 加这个属性，深度监听
    },
  },
  beforeDestroy() {
    const editor = this.editor;
    if (editor == null) return;
    editor.destroy(); // 组件销毁时，及时销毁编辑器
  },
  mounted() {
    console.log(this.data)
  },
  methods: {
    // 富文本确认
    onSubmitHtml() {
      let { html, MouseClickE, MouseClickIndex, data, htmltype } = this;
      if (htmltype == 1) {
        data[MouseClickE].labels[MouseClickIndex].content = html;
        this.data = data;
      }else{
        let obj = {
          x: MouseClickE.offsetX,
          y: MouseClickE.offsetY,
          content: html,
        };
        data[MouseClickIndex].labels.push(obj);
        this.data = data;
      }

      this.handleCloseHtml();
    },
    onCreated(editor) {
      this.editor = Object.seal(editor); // 一定要用 Object.seal() ，否则会报错
    },
    handleClose() {
      this.canvasObj.clear();
      
      this.dialogVisible = false;
      
    },
    handleCloseHtml(){
      this.html = "";
      this.MouseClickE = "";
      this.MouseClickIndex = "";
      this.htmltype = "";
      this.dialogVisibleText = false;
    },
    onDel(idx) {
      let { data } = this;
      this.$confirm(
        "删除图片后将删除本图片上的所有的备注信息，请谨慎操作！",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(() => {
        data.splice(idx, 1);
        this.data = data;
      });
    },
    // 删除
    onDelete(index, idx) {
      let { data } = this;
      this.$confirm("确定删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        data[index].labels.splice(idx, 1);
        this.data = data;
      });
    },
    // 编辑
    onEdit(index, idx, html) {
      // let { data } = this;
      this.htmltype = 1;
      this.html = html;
      this.MouseClickE = index;
      this.MouseClickIndex = idx;
      this.dialogVisibleText = true;
      // this.$confirm("确定删除?", "提示", {
      //   confirmButtonText: "确定",
      //   cancelButtonText: "取消",
      //   type: "warning",
      // }).then(() => {
      //   data[index].labels.splice(idx, 1);
      //   this.data = data;
      // });
    },
    MouseClick(e, index) {
      if (!this.disabled) {
        this.MouseClickE = e;
        this.MouseClickIndex = index;
        this.html = "";

        this.dialogVisibleText = true;
      }
    },
    // 保存
    async onSave() {
      this.loadingsave = true;
      let { data, index } = this;
      let dataURL = this.canvasObj.toDataURL({
        width: 1200,
        height: 600,
        left: 0,
        top: 0,
        format: "png",
      });
      let file = base64toFile(dataURL, "canvas");
      let res = await uploadHomeApiupload(file);
      let img = res.img;
      if (index >= 0) {
        data[index].img = img;
      } else {
        let obj = {
          title: "",
          img,
          labels: [],
        };

        data.push(obj);
      }
      this.data = data;
      this.dialogVisible = false;
      this.loadingsave = false;
      this.canvasObj.clear();
    },
    onClickDialog(index) {
      let { data, canvasObj } = this;
      this.index = index;
      this.dialogVisible = true;
      if (index >= 0) {
        if (canvasObj) {
          let imageUrl = data[index].img;
          this.setImage(imageUrl);
        } else {
          this.$nextTick(() => {
            this.canvasObj = new fabric.Canvas("label-canvas", {
              preserveObjectStacking: true, // 禁止选中图层时自定置于顶部
            });
          });
          let imageUrl = data[index].img;
          this.setImage(imageUrl);
        }
      } else {
        // let sss = this.canvasObj.getObjects();
        //   console.log("2222222");
        //   if (sss.length) {

        //     for (let index = 0; index < sss.length; index++) {
        //       await that.canvasObj.remove(sss[index]);
        //     }
        //   }
        if (!canvasObj) {
          this.$nextTick(() => {
            this.canvasObj = new fabric.Canvas("label-canvas", {
              preserveObjectStacking: true, // 禁止选中图层时自定置于顶部
            });
          });
        }
      }
    },
    beforeAvatarUpload(file) {
      let reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => {
        let _base64 = reader.result;
        let imageUrl = _base64;
        this.setImage(imageUrl);
      };
      return false;
    },
    setImage(imageUrl) {
      let imgCoord = fabric.Image.fromURL(imageUrl, (img) => {
        console.log("img", img);
        img.scale(1).set({
          left: 0,
          top: 0,
          angle: 0,
        });
        this.canvasObj.add(img).setActiveObject(img);
      });
    },
    // 移动层次
    moveActive: function (index) {
      let t = this.canvasObj.getActiveObject();
      console.log("选中的元素", t);
      switch (index) {
        case 0:
          t.sendBackwards(); //向下一层
          break;
        case 1:
          t.sendToBack(); //向下至底层
          break;
        case 2:
          t.bringForward(); //向上一层
          break;
        case 3:
          t.bringToFront(); //向上至顶层
          break;
        case 4:
          t.set({
            scaleX: t.scaleX * 0.5,
            scaleY: t.scaleY * 0.5,
          });
          this.canvasObj.renderAll();
          break;
        case 5:
          this.canvasObj.remove(t); //删除图片
          break;
        default:
          return;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.htmltext {
  border: 1px solid #cccccc;
  padding: 5px 10px;
  border-radius: 4px;
  width: calc(100% - 480px);
}
.dialogcanvas {
  display: flex;
  .dialogcanvas-operation {
    display: flex;
    flex-direction: column;
    align-items: center;
    .el-button {
      margin-top: 20px;
      width: 180px;
      margin-left: 20px;
    }
  }
  .dialogcanvas-canvas {
    border: 1px solid #efefef;
    width: 1200px;
    height: 600px;
  }
}
.process {
  background: #ffffff;
  border-radius: 8px;
  .process-title {
    display: flex;
    align-items: center;
    font-size: 20px;
    font-weight: 800;
    padding-bottom: 20px;
    > div:nth-child(1) {
      width: 4px;
      height: 26px;
      border-radius: 4px;
      background: #409eff;
      margin-right: 10px;
    }
  }
  .process-canvas {
    padding-top: 20px;
    margin-top: 20px;
    border-top: 1px dashed #efefef;
    display: flex;
    .process-canvas-left {
      width: 600px;
      .process-canvas-left-border {
        width: 600px;
        height: 300px;
        position: relative;
        border: 1px solid #efefef;
        .process-canvas-left-border-label {
          font-size: 12px;
          width: 20px;
          height: 20px;
          text-align: center;
          line-height: 20px;
          background: red;
          color: #ffffff;
          border-radius: 50%;
          position: absolute;
        }
        > img {
          // width: 300px;
          height: 300px;
        }
      }
      .process-canvas-left-edit {
        text-align: center;
        margin-top: 10px;
      }
    }
    .process-canvas-right {
      width: 100%;
      .process-canvas-right-div {
        display: flex;
        align-items: center;
        > div:nth-child(1) {
          width: 100px;
          padding-left: 20px;
          margin-top: 10px;
        }
        margin-bottom: 20px;
        .process-canvas-right-div-icon {
          display: flex;
        }
      }
    }
  }
  .process-content {
    .process-content-items {
      display: flex;
      align-items: center;
    }
    > div {
      display: flex;
      align-items: center;
      margin-bottom: 20px;
      > div:nth-child(2) {
        display: flex;
        align-items: center;
      }
    }
  }
  .process-position {
    display: flex;
    align-items: center;
    > div {
      display: flex;
      align-items: center;
      margin-bottom: 20px;
      > div:nth-child(1) {
        width: 140px;
        text-align: right;
        margin-right: 10px;
      }
      > .el-input {
        width: 400px;
      }
      > div:nth-child(2) {
        display: flex;
        align-items: center;
      }
    }
  }
}
</style>